package org.example.service;

import org.example.model.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class RedisSessionService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${spring.application.name}")
    private String serverId;

    private static final String USER_SESSION_KEY = "websocket:user:session:";
    private static final String SERVER_USERS_KEY = "websocket:server:users:";
    private static final long SESSION_TIMEOUT = 30; // 30分钟

    public void registerUserSession(String userId, String sessionId) {
        UserSession session = new UserSession(userId, serverId, sessionId);
        
        // 存储用户会话信息
        String userKey = USER_SESSION_KEY + userId;
        redisTemplate.opsForValue().set(userKey, session, SESSION_TIMEOUT, TimeUnit.MINUTES);
        
        // 存储服务器用户列表
        String serverKey = SERVER_USERS_KEY + serverId;
        redisTemplate.opsForSet().add(serverKey, userId);
        redisTemplate.expire(serverKey, SESSION_TIMEOUT, TimeUnit.MINUTES);
    }

    public void removeUserSession(String userId) {
        String userKey = USER_SESSION_KEY + userId;
        UserSession session = (UserSession) redisTemplate.opsForValue().get(userKey);
        
        if (session != null) {
            String serverKey = SERVER_USERS_KEY + session.getServerId();
            redisTemplate.opsForSet().remove(serverKey, userId);
        }
        
        redisTemplate.delete(userKey);
    }

    public UserSession getUserSession(String userId) {
        String userKey = USER_SESSION_KEY + userId;
        return (UserSession) redisTemplate.opsForValue().get(userKey);
    }

    public void updateHeartbeat(String userId) {
        String userKey = USER_SESSION_KEY + userId;
        UserSession session = (UserSession) redisTemplate.opsForValue().get(userKey);
        
        if (session != null) {
            session.updateHeartbeat();
            redisTemplate.opsForValue().set(userKey, session, SESSION_TIMEOUT, TimeUnit.MINUTES);
        }
    }

    public boolean isUserOnline(String userId) {
        String userKey = USER_SESSION_KEY + userId;
        return redisTemplate.hasKey(userKey);
    }

    public String getUserServer(String userId) {
        UserSession session = getUserSession(userId);
        return session != null ? session.getServerId() : null;
    }
}